package com.cqs.leetcode.ds.union.find;

public class QuickUnion implements IUnionFind {

    //表示的是链接:另外一个触点的名称
    private int[] ids;
    private int count;

    public QuickUnion(int n) {
        this.count = n;
        ids = new int[n];
        for (int i = 0; i < n; i++) {
            ids[i] = i;
        }
    }

    @Override
    public int find(int p) {
        while (p != ids[p]) {
            p = ids[p];
        }
        return p;
    }

    @Override
    public void union(int p, int q) {
        int proot = find(p);
        int qroot = find(q);
        if (proot != qroot) {
            ids[qroot] = proot;
            --count;
        }
    }

    @Override
    public int count() {
        return count;
    }

    @Override
    public boolean connected(int p, int q) {
        return find(p) == find(q);
    }
}
